﻿var setElStyle,
getElStyle,
fontFamilysData = [{
    id: "",
    name: "默认"
}];
for (name in fontFamilys) {
    fontFamilysData.push({
        id: fontFamilys[name],
        name: name
    })
}; (function ($) {
    var zIndex = 1,
    eventsStyle = {
        'display': '显示状态',
        'columnMargin': '列间距',
        'transition': '动画过渡',
        'default': '默认',
        'hover': '鼠标悬停',
        'active': '鼠标按下',
        'selected': '选中'
    },
    screenStyle = {
        'min1200': ' @media (min-width: 1200px)',
        '961_1199': ' @media (min-width: 961px) and (max-width: 1199px)',
        '768_960': ' @media (min-width: 768px) and (max-width: 960px)',
        '480_767': ' @media (min-width: 480px) and (max-width: 767px)',
        'max479': ' @media (max-width: 479px)'
    },
    unitSelect = [{
        id: 'px',
        name: 'px'
    },
    {
        id: '%',
        name: '%'
    },
    {
        id: '',
        name: '自动'
    }],
    getNewStyleEl = function (el, id) {
        var styleEl = $('<div id="' + id + '_style" data-styles="{}" style="display:none;"></div>');
        if (el == 'body') {
            styleEl.prependTo($('#body_static_style', pageLayout))
        } else if (el.attr('static')) {
            styleEl.prependTo($('#' + id + '_static_style', pageLayout))
        } else if (el.data('content') == 'json') {
            styleEl.prependTo(el.parent())
        } else {
            styleEl.prependTo(el)
        };
        return styleEl
    };
    setElStyle = function (el, selector, selectorName) {
        var selectorName = selectorName ? '-' + selectorName : '',
        id = el == 'body' ? 'body' : el.attr('id'),
        path = el == 'body' ? 'body' : el.attr('path'),
        styleId = id + '_style',
        idMix = '#' + id + (selector ? ' ' + selector : ''),
        styleEl,
        styles = {};
        if ($('#' + styleId, pageLayout).length) {
            styleEl = $('#' + styleId, pageLayout);
            styles = styleEl.data('styles')
        } else {
            styleEl = getNewStyleEl(el, id)
        };
        var activeContainer = $('div[role="toolsContainer"] >div.active', toolsMain),
        styleContainer = $('div[role=styleContainer][data-selector="' + selector + '"]', activeContainer),
        items = el == 'body' ? ['default'] : ['default', 'hover', 'active', 'selected'];
        styleContainer.css('position', 'relative');
        $('div[role="toolsTop"] ul[data-selector="' + selector + '"] li', activeContainer).each(function () {
            var type = $(this).data('type');
            $('<div role="itemsContainer" style="display:none;" data-type="' + type + '"><div class="h6 ct_2">设置“' + $('#pathPanel li.active').text() + selectorName + '”' + screensName[type] + '样式</div><form><div class="h6 ct_2" style="padding-top:20px;">样式加载中...</div></form></div>').appendTo(styleContainer)
        }).litabs({
            callBack: function (li) {
                clearTips(toolsMain);
                var num = li.data('i'),
                type = li.data('type'),
                itemsContainer = $('div[role="itemsContainer"]:eq(' + num + ')', styleContainer),
                init = function () {
                    li.data('init', 1);
                    $('form', itemsContainer).empty();
                    if (el != 'body') {
                        $('<div role="styleEvents" data-type="display"><dl class="setPanel"><dt><i class="trigon ct_3 small left"></i>' + eventsStyle['display'] + '</dt><dd><div  class="setPanelMain"><div class="pt10">&nbsp;&nbsp;' + '<label><input type="radio" value="" name="display_class_radio" />&nbsp;默认</label>&nbsp;&nbsp;' + '<label><input type="radio" value="show_' + type + '" name="display_class_radio" />&nbsp;显示</label>&nbsp;&nbsp;' + '<label><input type="radio" value="hide_' + type + '" name="display_class_radio" />&nbsp;隐藏</label>' + '</div></div></dd></dl></div>').appendTo($('form', itemsContainer));
                        $.each(items,
                        function (i, item) {
                            $('<div  role="styleEvents" data-type="' + item + '"><dl class="setPanel"><dt><i class="trigon ct_3 small left"></i>' + eventsStyle[item] + '</dt><dd><div  class="setPanelMain">' + $('#styleTemp').html() + '</div></dd></dl>').appendTo($('form', itemsContainer))
                        });
                        if (type == 'basic') {
                            $('<div role="styleEvents" data-type="transition"><dl class="setPanel"><dt><i class="trigon ct_3 small left"></i>' + eventsStyle['transition'] + '</dt><dd><div  class="setPanelMain"><div class="pt10">&nbsp;&nbsp;' + '<label><input type="radio" value="" name="transition_class_radio" />&nbsp;无动画</label>&nbsp;&nbsp;' + '<label><input type="radio" value="transition" name="transition_class_radio" />&nbsp;有动画</label>&nbsp;&nbsp;' + '</div></div></dd></dl></div>').appendTo($('form', itemsContainer))
                        };
                        if (path == 'row' || (path == 'app' && selector == '.con_body' && el.find('div.appRow').length)) {
                            $('<div role="styleEvents" data-type="columnMargin"><dl class="setPanel"><dt><i class="trigon ct_3 small left"></i>' + eventsStyle['columnMargin'] + '</dt><dd><div  class="setPanelMain">' + '<div class="setPanelRow pt10 clearfix">' + '<span class="setPanelText">间距</span>' + '<div class="setPanelInput">' + '<input type="text" name="column-margin" role="sliderNum" data-unit="px" class="small inputText" />' + '</div>' + '</div>' + '</div></dd></dl></div>').appendTo($('form', itemsContainer))
                        }
                    } else {
                        $('<div class="pt10"  role="styleEvents" data-type="default"></div>').append($('#styleTemp >div[data-body]').clone(true)).appendTo($('form', itemsContainer))
                    };
                    $('input[type="text"]', itemsContainer).fancyInput();
                    $('input[type="text"][name]', itemsContainer).on({
                        mouseenter: function () {
                            if (!$(this).val()) {
                                var CUEL = el == 'body' ? pageBody : $(idMix, pageBody),
                                name = $(this).attr('name'),
                                value;
                                if (name == 'column-margin') {
                                    if (path == 'row') {
                                        value = $(idMix + ' >div.rowPatch:first', pageBody).css('margin-left').replace('-', '')
                                    } else {
                                        value = $(idMix + ' >div.appRow >div:first', pageBody).css('margin-left').replace('-', '')
                                    }
                                } else {
                                    value = CUEL.css($(this).attr('name'))
                                };
                                if (!value) {
                                    return
                                } else if (value == 'transparent') {
                                    value = '透明'
                                } else if (name.indexOf('color') >= 0 && value.indexOf('a') < 0) {
                                    value = RGBToHex(value)
                                };
                                $(this).data({
                                    'tips': '3_t',
                                    'tipsTitle': '默认：' + value
                                }).showTips()
                            }
                        },
                        mouseleave: function () {
                            $(this).hideTips()
                        }
                    });
                    $('input[type="text"][role="sliderNum"]', itemsContainer).each(function () {
                        var $this = $(this),
                        selectEl,
                        setVal = function () {
                            var unit = selectEl ? selectEl.val() : '';
                            if (unit == '' && selectEl) {
                                $this.val('')
                            };
                            if (selectEl && unit != $this.data('unit')) {
                                $this.data('unit', unit);
                                var num = unit == '%' ? 100 : 1000;
                                $this.data('slider').slider('option', {
                                    min: $this.data('min') ? $this.data('min') : $this.data('minus') ? -num : 0,
                                    max: $this.data('max') ? $this.data('max') : num
                                })
                            };
                            changeStyle($this)
                        };
                        if ($this.data('unit') == 'select') {
                            var selectedPanel = $('<div class="setPanelUnit"></div>').insertAfter($this.parent());
                            selectEl = $('<select></select>').setSelect(unitSelect, 'px').appendTo(selectedPanel);
                            selectEl.change(setVal);
                            $this.data('selectEl', selectEl)
                        };
                        $this.on('blur',
                        function () {
                            var value = $this.val();
                            if (selectEl) {
                                if (!value) {
                                    $('option[value=""]', selectEl).attr('selected', true);
                                    $this.data('unit', 'auto')
                                } else if (value != '' && selectEl.val() == '') {
                                    $('option:eq(0)', selectEl).attr('selected', true)
                                }
                            };
                            setVal()
                        }).sliderNum({
                            slideOpts: {
                                min: $this.data('min') ? $this.data('min') : $this.data('minus') ? -100 : 0,
                                max: $this.data('max') ? $this.data('max') : 100,
                                step: $this.data('step') ? $this.data('step') : ''
                            },
                            change: function () {
                                var value = $this.val();
                                if (selectEl) {
                                    if (value != '' && selectEl.val() == '') {
                                        $('option:eq(0)', selectEl).attr('selected', true)
                                    }
                                };
                                setVal()
                            }
                        })
                    });
                    $('select[role="fontFamily"]', itemsContainer).setSelect(fontFamilysData);
                    setTimeout(setPanel, 50)
                },
                setPanel = function () {
                    getElStyle(el, selector, li.data('type'));
                    $('input[role="setColor"]', itemsContainer).each(function () {
                        var $this = $(this),
                        color = $this.val();
                        $this.on({
                            focus: function () {
                                $this.ColorPicker({
                                    color: color,
                                    onShow: function (colpkr) {
                                        $(colpkr).fadeIn(500);
                                        $('#frameMask').show();
                                        return false
                                    },
                                    onHide: function (colpkr) {
                                        $(colpkr).fadeOut(500);
                                        changeStyle($this);
                                        $('#frameMask').hide();
                                        return false
                                    },
                                    onChange: function (hsb, hex, rgb) {
                                        var newColor = '#' + hex;
                                        $this.val(newColor).prev().css('background-color', newColor)
                                    }
                                });
                                $this.ColorPickerShow()
                            }
                        });
                        var panel = $('<div style="float:left;line-height:24px; padding-left:5px;">' + ($this.data('clear') != 0 ? '<a class="icon-remove ct_2" role="clearColor" title="清空" data-tips="3_t"></a>&nbsp;' : '') + '<a class="icon-transparent ct_2 ' + ($(this).val() == 'transparent' ? 'active' : '') + '" role="transparent" title="透明" data-tips="3_t"></a></div>').insertAfter($this.parent());
                        panel.find('a[role="clearColor"]').on(click,
                        function () {
                            $this.val('').prev().css('background-color', '');
                            changeStyle($this)
                        });
                        panel.find('a[role="transparent"]').on(click,
                        function () {
                            $(this).toggleClass('active');
                            var value = $(this).hasClass('active') ? 'transparent' : '';
                            $this.val(value).prev().css('background-color', value);
                            changeStyle($this)
                        })
                    });
                    itemsContainer.delegate('input[type="text"][name]:not([role=sliderNum]):not([group=margin]):not([group=padding])', {
                        blur: function () {
                            var input = $(this),
                            name = input.attr('name'),
                            value = input.val();
                            if (input.attr('group') && input.parents('div[role="group"]:first').data('locked')) {
                                changeGroupStyle(input.parents('div[role="group"]:first'), input.attr('group'), input.val())
                            } else {
                                changeStyle(input)
                            };
                            if (name.indexOf('color') >= 0) {
                                input.prev().css('background-color', value)
                            }
                        }
                    }).delegate('input[group=margin],input[group=padding]', click,
                    function () {
                        openSlideWindow($(this))
                    }).delegate('input[type="radio"][name],input[type="checkbox"][name]', click,
                    function () {
                        changeStyle($(this))
                    }).delegate('select[name]:not([name="position"])', 'change',
                    function () {
                        changeStyle($(this))
                    }).delegate('select[name="position"]', 'change',
                    function () {
                        var positionSet = $(this).parents('div.addPanelList:first').find('div[role="positionSet"]');
                        if ($(this).val() == '') {
                            positionSet.hide();
                            $(':input', positionSet).val('')
                        } else {
                            positionSet.show();
                            $('input[name="z-index"]').val(zIndex)
                        };
                        if ($(this).parents('div[role="styleEvents"]:first').data('type') == 'default') {
                            var pValue = ($(this).val() == 'absolute' || $(this).val() == 'fixed') ? 'positionEl_' + type : '',
                            pContainer = $(this).parent().next();
                            if (!pContainer.length) {
                                pContainer = $('<div style="display:none;">' + '<input type="radio" value="" name="position_class_radio" group="position" />' + '<input type="radio" value="positionEl_' + type + '" name="position_class_radio" group="position"  />' + '</div>').insertAfter($(this).parent())
                            };
                            $('input[value="' + pValue + '"]', pContainer).attr('checked', true)
                        };
                        changeGroupStyle($(this).parents('div.addPanelList:first'), 'position', 'noSet')
                    }).delegate('div[role="positionSetIcon"] span', click,
                    function () {
                        var positionSet = $(this).parents('div.addPanelList:first').find('div[role="positionSet"]'),
                        position = $(this).data('position');
                        $(':input[name!="z-index"]', positionSet).val('');
                        for (name in position) {
                            $(':input[name="' + name + '"]', positionSet).val(0).data('unit', 'px').data('selectEl').val('px')
                        };
                        changeGroupStyle($(this).parents('div.addPanelList:first'), 'position', 'noSet')
                    }).delegate('i[role="lock"]', click,
                    function () {
                        var groupContainer = $(this).parents('div[role="group"]:first'),
                        group = $(this).data('group');
                        $(this).toggleClass('icon-lock2 icon-unlocked');
                        if ($(this).hasClass('icon-lock2')) {
                            groupContainer.data('locked', 1);
                            changeGroupStyle(groupContainer, group)
                        } else {
                            groupContainer.removeData('locked')
                        }
                    }).delegate('span[role="text-align"]', click,
                    function () {
                        $(this).toggleClass('active');
                        $(this).siblings().removeClass('active');
                        var input = $(this).siblings('select');
                        input.val($(this).hasClass('active') ? $(this).data('align') : '');
                        changeStyle(input)
                    }).delegate('span[role="text-style"]', click,
                    function () {
                        $(this).toggleClass('active');
                        var input = $(this).find('input');
                        input.val($(this).hasClass('active') ? $(this).data('style') : '');
                        changeStyle(input)
                    }).delegate('div[role="borderIcon"] span', click,
                    function () {
                        var $this = $(this),
                        role = $this.attr('role');
                        if ($this.hasClass('selected')) return;
                        $this.parents('div:first').find('span').removeClass('selected');
                        $this.addClass('selected').parents('div:first').next().find('div[role="' + role + '"]').show().siblings().hide()
                    }).delegate('div[role="borderStyleIcon"] span', click,
                    function () {
                        var $this = $(this);
                        if ($this.hasClass('active')) return;
                        var input = $this.siblings('input'),
                        style = $this.data('style');
                        $this.addClass('active').siblings('span').removeClass('active');
                        input.val(style);
                        changeStyle(input)
                    }).delegate('div[role="backgroundImageSet"] span[group]', click,
                    function () {
                        var $this = $(this);
                        if ($this.hasClass('active')) return;
                        var input = $this.siblings('input'),
                        value = $this.data('value');
                        $this.addClass('active').siblings('span').removeClass('active');
                        input.val(value);
                        changeStyle(input)
                    }).delegate('a[role="clearBackgroundImage"]', click,
                    function () {
                        var groupContainer = $(this).parents('div[group="backgroundImage"]:first');
                        $('input', groupContainer).val('');
                        changeGroupStyle(groupContainer, 'backgroundImage', 'noSet');
                        setBackgroundImagePanel(groupContainer, '');
                        $(this).hide()
                    }).delegate('a[role="transparentImage"]', click,
                    function () {
                        $(this).toggleClass('active');
                        var groupContainer = $(this).parents('div[group="backgroundImage"]:first'),
                        value = $(this).hasClass('active') ? 'none' : '';
                        $('input[name="background-image"]', groupContainer).val(value);
                        $('input:not([name="background-image"])', groupContainer).val('');
                        changeGroupStyle(groupContainer, 'backgroundImage', 'noSet');
                        setBackgroundImagePanel(groupContainer, '')
                    }).delegate('i[role="backgroundImageChange"]', click,
                    function () {
                        var groupContainer = $(this).parents('div[group="backgroundImage"]:first'),
                        input = $('input[name="background-image"]', groupContainer);
                        var fn = function (data) {
                            if (!(data && data[0])) return;
                            var src = data[0].src,
                            icon = data[0].icon || src;
                            input.val('url(' + src + ')');
                            $('div[role="backgroundImageSet"],a[role="clearBackgroundImage"]', groupContainer).show();
                            $('img[role="backgroundImageImg"]', groupContainer).show().attr('src', icon);
                            changeStyle(input)
                        };
                        top.openFinder({
                            callBack: fn,
                            pathList: ''
                        })
                    }).delegate('div[role="list-style"] span.btnGroupBtn', click,
                    function () {
                        $(this).toggleClass('active').siblings('span').removeClass('active');
                        var input = $(this).siblings('input'),
                        value = $(this).hasClass('active') ? $(this).data('value') : '';
                        input.val(value);
                        changeStyle(input)
                    })
                };
                itemsContainer.show().siblings().hide();
                if (!li.data('init')) {
                    setTimeout(init, 50)
                };
                if (li.attr('rulers')) {
                    setRulers(li.attr('rulers'))
                };
                resizeToolsScroll()
            }
        });
        styleContainer.delegate('dt', click,
        function (e) {
            $(this).find('>i').toggleClass('top left');
            $(this).next().find('>div').toggleClass('active');
            resizeToolsScroll()
        }).delegate('div.appToggle', click,
        function (e) {
            $(this).find('>i').toggleClass('top left');
            $(this).next().toggleClass('active');
            resizeToolsScroll()
        });
        var changeStyle = function ($this, noReset, enforce) {
            var value = $this.val();
            if ($this.data('input') == 'background-width' || $this.data('input') == 'background-height') {
                var groupContainer = $this.parents('div[role="backgroundImageSet"]:first'),
                widthInput = $('input[data-input="background-width"]', groupContainer),
                heightInput = $('input[data-input="background-height"]', groupContainer),
                input = $('input[name="background-size"]', groupContainer),
                width = widthInput.val() ? widthInput.val() + widthInput.data('unit') : 'auto',
                height = heightInput.val() ? heightInput.val() + heightInput.data('unit') : 'auto',
                size = (width == 'auto' && height == 'auto') ? '' : width + ' ' + height;
                input.val(size);
                checkStyle(input, noReset, enforce)
            } else if ($this.data('all')) {
                var group = $this.attr('group'),
                groupContainer = $this.parents('div[role="groupContainer"]:first');
                $('input[group="' + group + '"]', groupContainer).val(value);
                changeGroupStyle(groupContainer, group, 'noSet');
                if (group == 'radius') {
                    setBorderRadiusPanel(groupContainer)
                } else if (group.indexOf('border') == 0) {
                    setBorderPanel(groupContainer)
                }
            } else {
                checkStyle($this, noReset, enforce);
                if ($this.attr('group')) {
                    if ($this.attr('group') == 'radius') {
                        setBorderRadiusPanel($this.parents('div[role="groupContainer"]:first'))
                    } else if ($this.attr('group').indexOf('border') == 0) {
                        setBorderPanel($this.parents('div[role="groupContainer"]:first'))
                    }
                }
            }
        },
        changeGroupStyle = function (groupContainer, group, value) {
            var resetFlag = false,
            target;
            $.each(group.split(','),
            function (i, item) {
                var values = value ? value.toString().split(',')[i] : $(':input[name][group="' + item + '"]:eq(0)', groupContainer).val();
                $(':input[name][group="' + item + '"]:not([type="radio"]),input[name][group="' + item + '"][type="radio"]:checked', groupContainer).each(function () {
                    target = $(this);
                    if (value != 'noSet') {
                        target.val(values)
                    };
                    if (!resetFlag) {
                        resetFlag = checkStyle(target, 1)
                    } else {
                        checkStyle(target, 1)
                    }
                })
            });
            if (resetFlag) {
                checkStyle(target, 0, 1)
            }
        },
        checkStyle = function (target, noReset, enforce) {
            el = id == 'body' ? 'body' : $('#' + id, pageLayout);
            styleEl = $('#' + styleId, pageLayout);
            styles = styleEl.data('styles');
            var container = target.parents('div[role="itemsContainer"]:first'),
            type = container.data('type'),
            events = target.parents('div[role="styleEvents"]:first').data('type'),
            name = target.attr('name'),
            value = target.val(),
            unit = target.data('unit') || '',
            mix = target.data('mix'),
            flag = false;
            if (!styles[selector]) {
                styles[selector] = {}
            };
            if (!styles[selector][type]) {
                if (type == 'basic') {
                    styles[selector] = $.extend(true, {
                        basic: {}
                    },
                    styles[selector])
                } else {
                    styles[selector][type] = {}
                }
            };
            if (!styles[selector][type][events]) {
                styles[selector][type][events] = {}
            };
            if (value) {
                if (mix) {
                    if (value.indexOf(mix) < 0) {
                        value = value.replace('px', '') + unit
                    }
                } else {
                    value += unit
                }
            };
            if (styles[selector][type][events][name] != value) {
                if (value == '' && name.indexOf('_class') < 0) {
                    if (styles[selector][type][events][name]) {
                        delete styles[selector][type][events][name];
                        flag = true
                    }
                } else {
                    styles[selector][type][events][name] = value;
                    flag = true
                }
            };
            if ((flag && !noReset) || enforce) {
                resetStyle(styleEl, container, target);
                checkNews(target.parents('div[role="styleEvents"]:first'));
                change()
            };
            return flag
        },
        resetStyle = function (styleEl, container, target) {
            var html = '',
            style = $('style[selector="' + selector + '"]', styleEl);
            if (!style.length) {
                style = $('<style selector="' + selector + '"></style>').appendTo(styleEl)
            };
            for (type in styles[selector]) {
                var styleItems = styles[selector][type];
                if (type != 'basic') {
                    html += screenStyle[type] + '{'
                };
                for (events in styleItems) {
                    var eventsItems = styles[selector][type][events],
                    styleSelector = '',
                    aStyle = {},
                    ahoveStyle = {};
                    if (events == 'columnMargin') {
                        if (eventsItems['column-margin']) {
                            if (path == 'row') {
                                html += idMix + ' >div.rowPatch{margin-left:-' + eventsItems['column-margin'] + '}';
                                html += idMix + ' >div.rowPatch >div >.boxBlock{margin-left:' + eventsItems['column-margin'] + '}'
                            } else if (path == 'app') {
                                html += idMix + ' >div.appRow >div.appPatch{margin-left:-' + eventsItems['column-margin'] + '}';
                                html += idMix + ' >div.appRow >div >div >div.latticePad{margin-left:' + eventsItems['column-margin'] + '}'
                            }
                        }
                    } else {
                        if (events == 'default' || events == 'display') {
                            styleSelector = idMix
                        } else if (events == 'hover' || events == 'active') {
                            styleSelector = idMix + ':' + events
                        } else if (events == 'selected') {
                            styleSelector = idMix + '.' + events
                        };
                        html += styleSelector + '{';
                        for (name in eventsItems) {
                            if (name.indexOf('a_') >= 0) {
                                aStyle[name] = eventsItems[name]
                            } else if (name.indexOf('ahover_') >= 0) {
                                ahoveStyle[name] = eventsItems[name]
                            } else if (name.indexOf('_class') < 0) {
                                html += name + ':' + eventsItems[name] + ';';
                                if (name == 'overflow' && (eventsItems[name] == 'scroll' || eventsItems[name] == 'auto')) {
                                    html += '-webkit-overflow-scrolling:touch;'
                                }
                            } else {
                                var removeCls = '';
                                if (name.indexOf('_radio') >= 0) {
                                    $('div[data-type="' + events + '"][role="styleEvents"] :input[name="' + name + '"]:not(:checked)', container).each(function () {
                                        removeCls += $(this).val() + ' '
                                    })
                                };
                                $(idMix, pageLayout).removeClass(removeCls);
                                if (eventsItems[name]) {
                                    $(idMix, pageLayout).addClass(eventsItems[name])
                                };
                                if (el.attr('path') == 'app' && el.data('content') == 'json') {
                                    var data = el.data('data'),
                                    items = selector || 'self';
                                    if (!data['addClass']) {
                                        data['addClass'] = {}
                                    };
                                    data['addClass'][items] = ' ' + $(idMix, pageLayout).attr('class').replace('appWrapper', '').replace('currentTools', '').replace('selectedTools', '').replace('con_header', '').replace('con_body', '');
                                    el.removeData('data').attr('data-data', $.toJSON(data))
                                }
                            }
                        };
                        html += '} '
                    };
                    if (!$.isEmptyObject(aStyle)) {
                        html += styleSelector + ' a,' + styleSelector + ' a:link{';
                        for (name in aStyle) {
                            html += name.replace('a_', '') + ':' + aStyle[name] + ';'
                        };
                        html += '} '
                    };
                    if (!$.isEmptyObject(ahoveStyle)) {
                        html += styleSelector + ' a:hover{';
                        for (name in ahoveStyle) {
                            html += name.replace('ahover_', '') + ':' + ahoveStyle[name] + ';'
                        };
                        html += '} '
                    }
                };
                if (type != 'basic') {
                    html += '} '
                }
            };
            styleEl.removeData('styles').attr('data-styles', $.toJSON(styles));
            style.html(html)
        },
        openSlideWindow = function (input) {
            var unit = input.val().indexOf('%') >= 0 ? '%' : 'px',
            value = input.val().replace('%', '').replace('px', ''),
            top = input.offset().top - styleContainer.offset().top + input.outerHeight(),
            windowContainer = $('<div class="setWindow p15 ct_2" style="top:' + top + 'px">' + '<div class="setPanelRow h6 clearfix">' + '<span class="setPanelText" style="width:65px;">' + (input.data('settitle') || '') + '</span>' + '<div class="setPanelInput" style="width:60px;">' + '<input type="text" class="small inputText" data-unit="' + unit + '" value="' + value + '">' + '</div>' + ' </div>' + '</div>').appendTo(styleContainer).on(click,
            function (e) {
                $this.sliderNum('hide');
                e.stopPropagation();
                e.preventDefault()
            }),
            removeWindow = function () {
                $this.sliderNum('remove');
                windowContainer.remove();
                $(document).off(click, removeWindow)
            },
            $this = $('input', windowContainer),
            setVal = function () {
                var unit = selectEl ? selectEl.val() : '';
                if (unit == '' && selectEl) {
                    $this.val('')
                };
                if (selectEl) {
                    $this.data('unit', unit).data('slider').slider('option', {
                        min: unit == '%' ? -100 : -1000,
                        max: unit == '%' ? 100 : 1000
                    })
                };
                input.val(unit == '%' ? $this.val() + unit : $this.val());
                if (input.attr('group') && input.parents('div[role="group"]:first').data('locked')) {
                    changeGroupStyle(input.parents('div[role="group"]:first'), input.attr('group'), input.val())
                } else {
                    changeStyle(input)
                }
            };
            var selectedPanel = $('<div class="setPanelUnit"></div>').insertAfter($this.parent()),
            selectEl = $('<select></select>').setSelect(unitSelect, unit).appendTo(selectedPanel).change(setVal);
            $this.data('selectEl', selectEl).on('blur',
            function () {
                var value = $this.val();
                if (selectEl) {
                    if (!value) {
                        $('option[value=""]', selectEl).attr('selected', true);
                        $this.data('unit', 'auto')
                    } else if (value != '' && selectEl.val() == '') {
                        $('option:eq(0)', selectEl).attr('selected', true)
                    }
                };
                setVal()
            }).sliderNum({
                slideOpts: {
                    min: $this.data('min') ? $this.data('min') : unit == '%' ? -100 : -1000,
                    max: $this.data('max') ? $this.data('max') : unit == '%' ? 100 : 1000
                },
                change: function () {
                    var value = $this.val();
                    if (selectEl) {
                        if (value != '' && selectEl.val() == '') {
                            $('option:eq(0)', selectEl).attr('selected', true)
                        }
                    };
                    setVal()
                }
            });
            $this.focus();
            setTimeout(function () {
                $(document).on(click, removeWindow)
            },
            200)
        }
    },
    getElStyle = function (el, selector, screenType) {
        selector = selector || '';
        var id = el == 'body' ? 'body' : el.attr('id'),
        styleId = id + '_style',
        idMix = '#' + id + (selector ? ' ' + selector : ''),
        styleEl,
        styles = {};
        if ($('#' + styleId, pageLayout).length) {
            styleEl = $('#' + styleId, pageLayout);
            styles = styleEl.data('styles')
        } else {
            styleEl = getNewStyleEl(el, id)
        };
        if (!styles[selector]) return;
        var setStyleTools = function (screenType) {
            var container = $('div[role=styleContainer][data-selector="' + selector + '"] div[role="itemsContainer"][data-type=' + screenType + ']', toolsMain);
            if (container.length) {
                resetToolsContainer(container)
            };
            if (styles[selector][screenType]) {
                for (events in styles[selector][screenType]) {
                    var eventContainer = $('div[role="styleEvents"][data-type="' + events + '"]', container),
                    setRadius = false,
                    setBorder = false,
                    setBackground = false;
                    for (name in styles[selector][screenType][events]) {
                        var input = $(':input[name="' + name + '"]', eventContainer),
                        value = styles[selector][screenType][events][name],
                        unit = '';
                        if (!input.data('nounit')) {
                            if (value.indexOf('%') >= 0) {
                                unit = '%'
                            } else if (value.indexOf('px') >= 0) {
                                unit = 'px'
                            }
                        };
                        if (unit) {
                            value = value.replace('px', '').replace('%', '');
                            if (input.data('mix') == unit) {
                                input.val(value + unit)
                            } else if (name != 'background-size') {
                                input.data('unit', unit).val(value)
                            };
                            if (input.length == 1 && input.data('selectEl')) {
                                $('option[value="' + unit + '"]', input.data('selectEl')).attr('selected', true)
                            }
                        } else {
                            setInputValue(name, value, eventContainer);
                            if (name == 'position') {
                                var positionSet = eventContainer.find('div[role="positionSet"]');
                                positionSet.show()
                            };
                            if (name.indexOf('color') >= 0) {
                                input.prev().css('background-color', value);
                                if (value == 'transparent') {
                                    input.parents('div.setPanelRow').find('a[role="transparent"]').addClass('active')
                                }
                            };
                            if (name == 'text-align') {
                                input.siblings('span[data-align="' + value + '"]').addClass('active')
                            };
                            if ($.inArray(name, ['font-weight', 'font-style', 'text-decoration']) >= 0) {
                                input.parent().addClass('active')
                            }
                        };
                        if (name.indexOf('border') >= 0) {
                            if (name.indexOf('radius') >= 0) {
                                setRadius = true
                            } else {
                                setBorder = true
                            }
                        } else if (name == 'background-image') {
                            setBackground = true
                        }
                        if (name.indexOf('list-style') >= 0) {
                            input.siblings('span[data-value="' + value + '"]').addClass('active')
                        }
                    };
                    if (setRadius) {
                        setBorderRadiusPanel(eventContainer)
                    };
                    if (setBorder) {
                        setBorderPanel(eventContainer, 1)
                    };
                    if (setBackground) {
                        setBackgroundImagePanel(eventContainer, 1)
                    }
                };
                checkNews(container)
            }
        },
        resetToolsContainer = function (container) {
            $('input[type="text"],select', container).val('');
            $('input[type="radio"],input[type="checkbox"]', container).attr('checked', false);
            $('div[role="positionSet"]', container).hide();
            $('i[role="colorSquare"]', container).css('background-color', '');
            $('div[role="backgroundImageSet"],a[role="clearBackgroundImage"]', container).hide();
            $('img[role="backgroundImageImg"]', container).hide().attr('src', '');
            $('a[role]', container).removeClass('active');
            $('span.btnGroupBtn,span[group],div[role="borderStyleIcon"] span', container).removeClass('active')
        };
        if (screenType) {
            setStyleTools(screenType)
        } else {
            $('div[role=styleContainer][data-selector="' + selector + '"] div[role="itemsContainer"]', toolsMain).each(function () {
                setStyleTools($(this).data('type'))
            })
        }
    },
    setBackgroundImagePanel = function (eventContainer, flag) {
        var container = $('div[role="backgroundImageSet"]', eventContainer);
        if (!flag) {
            $('span[group]', container).removeClass('active')
        };
        input = $('input[name="background-image"]', eventContainer);
        if (input.val() && input.val() != 'none') {
            $('div[role="backgroundImageSet"],a[role="clearBackgroundImage"]', eventContainer).show();
            input.siblings('img').show().attr('src', input.val().replace('url(', '').replace(')', '').replace('pic', 'icon'))
        } else {
            $('div[role="backgroundImageSet"],a[role="clearBackgroundImage"],img', eventContainer).hide();
            if (input.val() == 'none') {
                $('a[role="transparentImage"]', eventContainer).addClass('active')
            }
        };
        var sizeInput = $('input[name="background-size"]', container),
        sizeValue = sizeInput.val();
        if (sizeValue) {
            var width = sizeValue.split(' ')[0],
            height = sizeValue.split(' ')[1],
            widthUnit = width.indexOf('px') >= 0 ? 'px' : width == 'auto' ? '' : '%',
            heightUnit = height.indexOf('px') >= 0 ? 'px' : height == 'auto' ? '' : '%',
            widthInput = $('input[data-input="background-width"]', container),
            heightInput = $('input[data-input="background-height"]', container);
            widthInput.val(width.replace(widthUnit, '').replace('auto', '')).data('unit', widthUnit);
            heightInput.val(height.replace(heightUnit, '').replace('auto', '')).data('unit', heightUnit);
            $('option[value="' + widthUnit + '"]', widthInput.data('selectEl')).attr('selected', true);
            $('option[value="' + heightUnit + '"]', heightInput.data('selectEl')).attr('selected', true)
        };
        $('input[data-btn]', container).each(function () {
            $(this).siblings('span[data-value="' + $(this).val() + '"]').addClass('active')
        })
    },
    setBorderPanel = function (eventContainer, flag) {
        var container = $('div.setBorderWrapper', eventContainer),
        borders = ['border-style', 'border-width', 'border-color'],
        toggles = false;
        if (!flag) {
            $('div[role="borderStyleIcon"] span', container).removeClass('active')
        };
        $.each(borders,
        function (j, item) {
            var aValue = '',
            toggle = false;
            $('input[name][group="' + item + '"]', container).each(function (i) {
                if (i == 0) {
                    aValue = $(this).val()
                } else {
                    if (aValue != $(this).val()) {
                        toggle = true
                    }
                };
                $('span[group][role="' + $(this).parents('div.setBorderInfo').attr('role') + '"]', container).addClass('active');
                if (item == 'border-style') {
                    $(this).siblings('span[data-style="' + $(this).val() + '"]').addClass('active')
                } else if (item == 'border-color') {
                    $(this).prev().css('background-color', $(this).val())
                }
            });
            var allInput = $('input[group="' + item + '"][data-all="1"]', container);
            if (toggle) {
                allInput.val('');
                if (item == 'border-style') {
                    allInput.siblings('span').removeClass('active')
                } else if (item == 'border-color') {
                    allInput.prev().css('background-color', '')
                };
                toggles = true
            } else {
                allInput.val(aValue);
                if (item == 'border-style') {
                    allInput.siblings('span[data-style="' + aValue + '"]').addClass('active')
                } else if (item == 'border-color') {
                    allInput.prev().css('background-color', aValue)
                }
            }
        });
        if (toggles) {
            $('span[group][role="all"]', container).removeClass('active')
        } else {
            $('span[group][role="all"]', container).addClass('active');
            $('span[group][role!="all"]', container).removeClass('active')
        }
    },
    setBorderRadiusPanel = function (eventContainer) {
        var container = $('div.setBorderRadiusWrapper', eventContainer),
        aValue = '',
        toggle = false;
        $('input[name]', container).each(function (i, item) {
            if (i == 0) {
                aValue = $(this).val()
            } else {
                if (aValue != $(this).val()) {
                    toggle = true
                }
            };
            $('span[group][role="' + $(this).data('btn') + '"]', container).addClass('active')
        });
        if (toggle) {
            $('span[group][role="all"]', container).removeClass('active');
            $('input[data-all="1"]', container).val('')
        } else {
            $('span[group][role!="all"]', container).removeClass('active');
            $('span[group][role="all"]', container).addClass('active');
            $('input[data-all="1"]', container).val(aValue)
        }
    },
    checkNews = function (container) {
        $('div.setBlock', container).each(function () {
            var div = $(this);
            if ($(':input[name]:checked:not([value=""]),select[name] option:selected:not([value=""]),:input:[type="text"][name]:not([value=""])', div).length) {
                if (!$('>div i.setNewIcon', div).length) {
                    $('>div:first', div).append('<span class="fr pt5"><i class="setNewIcon"></i></span>')
                }
            } else {
                if ($('>div i.setNewIcon', div).length) {
                    $('>div >span', div).remove()
                }
            }
        });
        $('dl.setPanel', container).each(function () {
            var dl = $(this);
            if ($(':input[name]:checked:not([value=""]),select[name] option:selected:not([value=""]),:input:[type="text"][name]:not([value=""])', dl).length) {
                if (!$('>dt i.setNewIcon', dl).length) {
                    $('>dt:first', dl).append('<span class="fr pt5"><i class="setNewIcon"></i></span>')
                }
            } else {
                if ($('>dt i.setNewIcon', dl).length) {
                    $('>dt >span', dl).remove()
                }
            }
        })
    };
    $.fn.sliderNum = function (opts, set, val) {
        return this.each(function () {
            if (typeof opts == 'string') {
                if (opts == 'slider') {
                    return '11'
                };
                if ($(this).data('sliderObj') && typeof $(this).data('sliderObj')[opts] == 'function') {
                    return ($(this).data('sliderObj')[opts](set, val))
                };
                return
            };
            var self = this,
            $this = $(this),
            isShow = false,
            options = $.extend(true, {
                buttonClass: 'sliderButton',
                containerClass: 'sliderContainer',
                panelClass: 'sliderPanel',
                slide: $.noop,
                change: $.noop,
                stop: $.noop,
                slideOpts: {}
            },
            opts),
            slideOpts = $.extend(true, {
                orientation: 'vertical',
                max: 100,
                min: 0,
                value: $this.val(),
                slide: function (event, ui) {
                    $this.val(ui.value);
                    options.slide($this, event, ui)
                },
                change: function (event, ui) {
                    $this.val(ui.value);
                    options.change($this, event, ui)
                },
                stop: function (event, ui) {
                    $this.val(ui.value);
                    options.stop($this, event, ui)
                }
            },
            options.slideOpts),
            target = $('<span class="' + options.buttonClass + '"></span>').insertAfter($this),
            sliderContainer = $('<div class="' + options.containerClass + '"><div class="' + options.panelClass + '"><div role="slideBar"></div></div></div>');
            sliderContainer.hide().appendTo('body').css({
                zIndex: 10001
            }).find('div[role="slideBar"]').slider(slideOpts);
            $this.data('slider', $('div[role="slideBar"]', sliderContainer));
            this.show = function () {
                if (!sliderContainer) {
                    self.create()
                } else {
                    var left = target.offset().left,
                    top = target.offset().top + Math.floor(target.outerHeight() / 2) - Math.floor(sliderContainer.outerHeight() / 2);
                    if (top < 0) {
                        top = 0
                    } else if (top + sliderContainer.outerHeight() > $(document).height()) {
                        top = $(document).height() - sliderContainer.outerHeight()
                    };
                    sliderContainer.show().css({
                        left: left,
                        top: top
                    });
                    var num = $this.val() || 0;
                    $this.data('slider').slider('value', num)
                };
                isShow = true
            };
            this.hide = function () {
                if (isShow && sliderContainer) {
                    sliderContainer.hide()
                };
                isShow = false
            };
            this.remove = function () {
                if (sliderContainer) {
                    sliderContainer.remove();
                    target.remove();
                    $(document).off(click, _hide);
                    $this.removeData('sliderObj')
                }
            };
            var _hide = function () {
                self.hide()
            },
            _autoValue = function () {
                var val = $this.val();
                if ((!isNaN(val)) && val >= options.slideOpts.min && val <= options.slideOpts.max) {
                    $this.data('slider').slider('value', val)
                }
            };
            target.on('click',
            function (e) {
                self.show();
                e.stopPropagation()
            });
            $(document).on(click, _hide);
            $this.data('sliderObj', self)
        })
    }
})(jQuery);